<template>
  <div>
    <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle">
      <BasicForm @register="registerForm" />

      <template #footer>
        <Space :size="8">
          <a-button @click="handleClose"> 取消 </a-button>
          <a-button type="success" @click="handleSave"> 保存 </a-button>
          <a-button type="primary" @click="handleSubmit"> 提交 </a-button>
        </Space>
      </template>
    </BasicModal>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, watch, ComputedRef } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { formSchemaCommercial, formSchemaResident } from './editPlace.data';
  import { Tabs, Space, Upload, Divider, Tag, Avatar, Tooltip } from 'ant-design-vue';
  import {
    editFireCommercialPlaceInfo,
    editFireResidentPlaceInfo,
    submitResidentPlace,
    submitCommercialPlace,
    submitCheckResidentPlace,
    submitCheckCommercialPlace,
  } from '/@/api/demo/system';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import type { UploadProps } from 'ant-design-vue';
  import { createImgPreview, ImagePreview } from '/@/components/Preview/index';
  import { useGlobSetting } from '/@/hooks/setting';
  import { FileItem } from '/@/components/Upload/src/typing';
  const globSetting = useGlobSetting();
  import { uploadImage } from '/@/api/sys/upload';
  import { useUserStore } from '/@/store/modules/user';
  const userStore = useUserStore();
  const tk = userStore.getToken;

  export default defineComponent({
    name: 'AddPlaceModal',
    components: { BasicModal, BasicForm, Space, Upload, PlusOutlined, ImagePreview },
    props: {
      placeType: {
        type: Number,
        default: 0,
      },
      modeType: {
        type: Number,
        default: 0,
      },
    },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const isUpdate = ref(true);
      const editId = ref('');
      const editHId = ref('');
      const editRecord = ref({});
      const fileList = ref<UploadProps['fileList']>([]);

      const uploadFileRecord = ref({});
      function formSchemaGet() {
        let fss: FormSchema[] = [];
        if (0 == props.placeType) {
          fss = formSchemaResident(props.modeType, uploadFileRecord.value);
        } else {
          fss = formSchemaCommercial(props.modeType, uploadFileRecord.value);
        }

        return fss;
      }

      let formschemas: ComputedRef<FormSchema[]> = computed(formSchemaGet);
      const [
        registerForm,
        { resetFields, setFieldsValue, updateSchema, validate, getFieldsValue, clearValidate },
      ] = useForm({
        labelWidth: '50%',
        labelAlign: 'left',
        schemas: formschemas,
        showActionButtonGroup: false,
      });

      function adjustValues(fss: FormSchema[], record: any) {
        if (fss) {
          fss.forEach((ele) => {
            if (ele.field.startsWith('_')) {
              const val = record[ele.field.substring(1)];
              if (val) {
                const valObj = JSON.parse(val);
                if (valObj.list) {
                  const valObj2: string[] = [];
                  valObj.list.forEach((element) => {
                    if (element.checked) {
                      valObj2.push(element.title);
                    }
                  });
                  if ('CheckboxGroup' == ele.component) {
                    record[ele.field] = valObj2;
                  } else if ('RadioGroup' == ele.component) {
                    if (valObj2.length > 0) {
                      record[ele.field] = valObj2[valObj2.length - 1];
                    }
                  } else if ('Select' == ele.component) {
                    if (valObj2.length > 0) {
                      record[ele.field] = valObj2[valObj2.length - 1];
                    }
                  }
                }
              }
            }
          });
        }
        return record;
      }

      async function uploadApiByItem(item: FileItem) {
        console.log(item);
        if (item.originFileObj) {
          const { data } = await uploadImage(item.originFileObj);
          if (data.succ) return data.data;
        }

        if (item instanceof File) {
          const { data } = await uploadImage(item);
          if (data.succ) return data.data;
        }
        if (item) {
          return item.uid;
        }

        return null;
      }

      async function rebuildValues(fss: FormSchema[], record: any) {
        fss.forEach((ele) => {
          if (ele.field.startsWith('_')) {
            const val = record[ele.field];
            const eleComponentProps: any = ele.componentProps;
            if (val) {
              if ('CheckboxGroup' == ele.component) {
                const valObj2: any[] = [];
                eleComponentProps.options.forEach((element) => {
                  valObj2.push({
                    checked: val.includes(element.value),
                    code: '',
                    title: element.value,
                  });
                });
                record[ele.field.substring(1)] = JSON.stringify({ list: valObj2 });
              } else if ('RadioGroup' == ele.component) {
                const valObj2: any[] = [];
                eleComponentProps.options.forEach((element) => {
                  valObj2.push({
                    checked: val == element.value,
                    code: '',
                    title: element.value,
                  });
                });
                record[ele.field.substring(1)] = JSON.stringify({ list: valObj2 });
              } else if ('Select' == ele.component) {
                const valObj2: any[] = [];
                eleComponentProps.options.forEach((element) => {
                  valObj2.push({
                    checked: val == element.value,
                    code: '',
                    title: element.value,
                  });
                });
                record[ele.field.substring(1)] = JSON.stringify({ list: valObj2 });
              }
            }
          }

          if (ele.component == 'Checkbox') {
            if (null == record[ele.field]) {
              record[ele.field] = false;
            }
          }
        });

        for (var i in uploadFileRecord.value) {
          const vi = uploadFileRecord.value[i];
          if (vi && vi.length > 0) {
            const data = await Promise.all(
              vi.map((item) => {
                return uploadApiByItem(item);
              }),
            );

            const vailds = data.filter(Boolean);
            if (vailds.length > 0) {
              record[i] = vailds;
            }
          } else {
            record[i] = null;
          }
        }

        return record;
      }

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false, destroyOnClose: true });
        fileList.value = [];
        isUpdate.value = !!data?.isUpdate;
        editId.value = data.record.id;
        editHId.value = data.record.houseId;
        editRecord.value = data.record;
        const adj = adjustValues(formschemas.value, data.record);
        if (unref(isUpdate)) {
          setFieldsValue({
            ...adj,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '场所消防信息录入' : '场所消防信息录入'));

      function handleClose() {
        closeModal();
      }

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          values.id = editId.value;
          values.houseId = editHId.value;
          values.location = editRecord.value.location;
          await rebuildValues(formschemas.value, values);
          // TODO custom api
          if (unref(isUpdate)) {
            if (0 == props.placeType) {
              if (0 == props.modeType) {
                await editFireResidentPlaceInfo(values);
                await submitResidentPlace(values);
              } else {
                await submitCheckResidentPlace(values);
              }
            } else {
              if (0 == props.modeType) {
                await editFireCommercialPlaceInfo(values);
                await submitCommercialPlace(values);
              } else {
                await submitCheckCommercialPlace(values);
              }
            }
          } else {
            //await addPlaceList(values);
          }
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      async function handleSave() {
        try {
          await clearValidate();
          const values = await getFieldsValue();
          setModalProps({ confirmLoading: true });
          values.id = editId.value;
          values.houseId = editHId.value;
          values.location = editRecord.value.location;
          values.isCheckWork = 1==props.modeType;
          await rebuildValues(formschemas.value, values);
          // TODO custom api
          if (unref(isUpdate)) {
            if (0 == props.placeType) {
              await editFireResidentPlaceInfo(values);
            } else {
              await editFireCommercialPlaceInfo(values);
            }
          } else {
            //await addPlaceList(values);
          }
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
        handleSave,
        handleClose,
      };
    },
  });
</script>
